from flask import Flask, render_template, jsonify, request
import os
import json
import jwt

app = Flask(__name__)
app.jinja_env.variable_start_string = '[['
app.jinja_env.variable_end_string = ']]'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/api/user/login', methods=['POST'])
def login():
    data = request.get_json()

    db_file = os.path.join(os.path.abspath(
        os.path.dirname(__file__)), 'db.json')
    with open(db_file) as db_json:
        db = json.load(db_json)
    users = db['users']

    if 'username' not in data or str(data['username']).strip() == '':
        return jsonify({
            'code': -1,
            'msg': '用户名不能为空'
        })

    if 'password' not in data or str(data['password']).strip() == '':
        return jsonify({
            'code': -1,
            'msg': '密码不能为空'
        })

    current_user = next(
        filter(lambda item: item['username'] == data['username'], users), None)
    if current_user is None:
        return jsonify({
            'code': -1,
            'msg': '用户不存在'
        })
    if current_user['password'] != data['password']:
        return jsonify({
            'code': -1,
            'msg': '密码错误'
        })

    token = jwt.encode(
        {"username": current_user['username']}, "test_secret", algorithm="HS256")

    return jsonify({
        'code': 0,
        'msg': '登录成功',
        'data': {
            'username': current_user['username'],
            'token': token
        }
    })


@app.route('/api/user/me')
def me():
    token = request.headers.get('x-token')
    try:
        data = jwt.decode(token, "test_secret", algorithms=["HS256"])
        return jsonify({
            'code': 0,
            'msg': '获取成功',
            'data': data
        })
    except:
        return jsonify({
            'code': -1,
            'msg': '获取失败',
        })


if __name__ == '__main__':
    app.run(debug=True, port=5000)
